{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-09-08T02:33:54.017646Z",
     "start_time": "2025-09-08T02:33:54.006564Z"
    }
   },
   "source": [
    "from torch.nn import MSELoss\n",
    "from torch.utils import data\n",
    "from d2l import torch as d2l\n",
    "import torch\n",
    "\n",
    "true_w = torch.tensor([2, -3.4])\n",
    "true_b = 4.2\n",
    "print(len(true_w))\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000)\n",
    "print(features.shape)\n",
    "\n",
    "def load_array(data_arrays, batch_size, is_train=True):\n",
    "    dataset = data.TensorDataset(*data_arrays)\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n",
    "\n",
    "batch_size = 10\n",
    "data_iter = load_array((features, labels), batch_size)\n",
    "\n",
    "next(iter(data_iter))\n"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "torch.Size([1000, 2])\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[tensor([[-1.3238,  0.5681],\n",
       "         [ 0.9629, -1.1073],\n",
       "         [ 0.3401, -0.3144],\n",
       "         [ 0.3903,  0.0378],\n",
       "         [-0.2333,  0.6130],\n",
       "         [-1.2551, -0.4270],\n",
       "         [-0.4905, -0.5001],\n",
       "         [ 0.1476,  0.0882],\n",
       "         [-1.3638, -0.2433],\n",
       "         [-0.9744,  0.7230]]),\n",
       " tensor([[-0.3833],\n",
       "         [ 9.8986],\n",
       "         [ 5.9584],\n",
       "         [ 4.8632],\n",
       "         [ 1.6306],\n",
       "         [ 3.1420],\n",
       "         [ 4.9241],\n",
       "         [ 4.2011],\n",
       "         [ 2.2909],\n",
       "         [-0.2177]])]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-08T02:23:03.743303Z",
     "start_time": "2025-09-08T02:23:03.735056Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch import nn\n",
    "\n",
    "net = nn.Sequential(nn.Linear(2, 1))\n",
    "\n",
    "# 初始化参数\n",
    "net[0].weight.data.normal_(0, 0.01)\n",
    "net[0].bias.data.fill_(0)"
   ],
   "id": "3cfda6ae998344c",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-08T02:34:10.465711Z",
     "start_time": "2025-09-08T02:34:10.459981Z"
    }
   },
   "cell_type": "code",
   "source": [
    "loss = nn.MSELoss()\n",
    "optimizer = torch.optim.SGD(net.parameters(), lr=0.03)"
   ],
   "id": "7a575e26e369388e",
   "outputs": [],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-08T02:34:12.428390Z",
     "start_time": "2025-09-08T02:34:12.335356Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 训练\n",
    "epochs = 3\n",
    "for epoch in range(epochs):\n",
    "    for X, y in data_iter:\n",
    "        l = loss(net(X), y)\n",
    "        optimizer.zero_grad()\n",
    "        l.backward()\n",
    "        optimizer.step()\n",
    "    l = loss(net(features), labels)\n",
    "    print(f'epoch: {epoch}, train loss: {l.item(): f}')"
   ],
   "id": "e90c6968e8b96feb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, train loss:  0.000357\n",
      "epoch: 1, train loss:  0.000103\n",
      "epoch: 2, train loss:  0.000104\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-08T02:34:27.925981Z",
     "start_time": "2025-09-08T02:34:27.916471Z"
    }
   },
   "cell_type": "code",
   "source": [
    "w = net[0].weight.data\n",
    "print('w的估计误差：', true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print('b的估计误差：', true_b - b)"
   ],
   "id": "f09c26c8bf53225b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差： tensor([0.0012, 0.0005])\n",
      "b的估计误差： tensor([0.0011])\n"
     ]
    }
   ],
   "execution_count": 19
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
